<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 数据统计卡片 -->
      <el-col :span="6" v-for="(item, index) in statisticsData" :key="index">
        <el-card class="statistic-card" shadow="hover">
          <div class="statistic-icon" :class="item.iconClass">
            <el-icon><component :is="item.icon" /></el-icon>
          </div>
          <div class="statistic-info">
            <div class="statistic-title">{{ item.title }}</div>
            <div class="statistic-value">{{ item.value }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 最近仓储记录 -->
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>最近仓储记录</span>
              <el-button text @click="navigateTo('/storage-records')">
                查看全部
              </el-button>
            </div>
          </template>
          <el-table :data="recentStorageRecords" style="width: 100%" v-loading="recordsLoading">
            <el-table-column label="货物编号" prop="cargoId" width="120" />
            <el-table-column label="入库时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.entryTime) }}
              </template>
            </el-table-column>
            <el-table-column label="存储天数" prop="actualDays" />
          </el-table>
        </el-card>
      </el-col>

      <!-- 港口区域使用率 -->
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>未支付费用</span>
              <el-button text @click="navigateTo('/storage-fees')">
                查看全部
              </el-button>
            </div>
          </template>
          <div v-loading="feesLoading" style="height: 300px; padding: 10px; overflow-y: auto;">
            <template v-if="unpaidFees.length > 0">
              <el-table :data="unpaidFees" style="width: 100%">
                <el-table-column label="费用ID" prop="feeId" width="80" />
                <el-table-column label="金额" prop="feeAmount" width="100">
                  <template #default="scope">
                    ¥{{ scope.row.feeAmount }}
                  </template>
                </el-table-column>
                <el-table-column label="计费日期">
                  <template #default="scope">
                    {{ formatDate(scope.row.calculationDate) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="scope">
                    <el-button type="primary" link size="small" @click="handleViewFeeDetail(scope.row)">
                      详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
            <el-empty v-else description="暂无未支付费用" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 区域使用情况 -->
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>港口区域情况</span>
              <el-button text @click="navigateTo('/port-areas')">
                查看全部
              </el-button>
            </div>
          </template>
          <el-table :data="portAreas" style="width: 100%" v-loading="areasLoading">
            <el-table-column label="区域编号" prop="areaCode" width="120" />
            <el-table-column label="区域名称" prop="areaName" width="150" />
            <el-table-column label="区域类型" prop="areaType" width="120" />
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="使用率" width="220">
              <template #default="scope">
                <el-progress 
                  :percentage="calculateUsage(scope.row)" 
                  :color="getUsageColor(calculateUsage(scope.row))"
                />
              </template>
            </el-table-column>
            <el-table-column label="当前使用/最大容量">
              <template #default="scope">
                {{ scope.row.currentUsage }} / {{ scope.row.maxCapacity }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

export default {
  name: 'Dashboard',
  setup() {
    const router = useRouter()
    const store = useStore()
    
    // 加载状态
    const recordsLoading = ref(false)
    const areasLoading = ref(false)
    const feesLoading = ref(false)
    
    // 数据统计
    const statisticsData = reactive([
      { title: '客户总数', value: 0, icon: 'User', iconClass: 'blue-bg' },
      { title: '货物总数', value: 0, icon: 'Box', iconClass: 'orange-bg' },
      { title: '区域总数', value: 0, icon: 'Location', iconClass: 'green-bg' },
      { title: '仓储记录', value: 0, icon: 'Document', iconClass: 'purple-bg' }
    ])
    
    // 最近仓储记录
    const recentStorageRecords = ref([])
    
    // 港口区域数据
    const portAreas = ref([])
    
    // 未支付费用数据
    const unpaidFees = ref([])
    
    // 初始化数据
    onMounted(async () => {
      await fetchStatisticsData()
      await fetchRecentStorageRecords()
      await fetchPortAreas()
      await fetchUnpaidFees()
    })
    
    // 获取统计数据
    const fetchStatisticsData = async () => {
      try {
        // 获取客户总数
        const clients = await store.dispatch('fetchClients')
        statisticsData[0].value = clients.length
        
        // 获取货物总数
        const cargos = await store.dispatch('fetchCargos')
        statisticsData[1].value = cargos.length
        
        // 获取区域总数
        const areas = await store.dispatch('fetchPortAreas')
        statisticsData[2].value = areas.length
        
        // 获取仓储记录总数
        const records = await store.dispatch('fetchStorageRecords')
        statisticsData[3].value = records.length
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    }
    
    // 获取最近仓储记录
    const fetchRecentStorageRecords = async () => {
      recordsLoading.value = true
      try {
        const records = await store.dispatch('fetchStorageRecords')
        // 排序并取最近5条
        recentStorageRecords.value = records
          .sort((a, b) => new Date(b.entryTime) - new Date(a.entryTime))
          .slice(0, 5)
      } catch (error) {
        console.error('获取最近仓储记录失败:', error)
      } finally {
        recordsLoading.value = false
      }
    }
    
    // 获取港口区域数据
    const fetchPortAreas = async () => {
      areasLoading.value = true
      try {
        portAreas.value = await store.dispatch('fetchPortAreas')
      } catch (error) {
        console.error('获取港口区域数据失败:', error)
      } finally {
        areasLoading.value = false
      }
    }
    
    // 获取未支付费用数据
    const fetchUnpaidFees = async () => {
      feesLoading.value = true
      try {
        const fees = await store.dispatch('fetchUnpaidFees')
        unpaidFees.value = fees
      } catch (error) {
        console.error('获取未支付费用数据失败:', error)
        unpaidFees.value = []
      } finally {
        feesLoading.value = false
      }
    }
    
    // 计算使用率
    const calculateUsage = (area) => {
      if (!area.maxCapacity || area.maxCapacity === 0) return 0
      return Math.round((area.currentUsage / area.maxCapacity) * 100)
    }
    
    // 获取使用率颜色
    const getUsageColor = (percentage) => {
      if (percentage < 70) return ''
      if (percentage < 90) return '#E6A23C'
      return '#F56C6C'
    }
    
    // 获取状态标签类型
    const getStatusType = (status) => {
      switch (status) {
        case '可用':
          return 'success'
        case '维护':
          return 'warning'
        case '已满':
          return 'danger'
        default:
          return 'info'
      }
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 导航到指定路由
    const navigateTo = (path) => {
      console.log('navigateTo被调用，路径:', path)
      try {
        router.push(path)
      } catch (error) {
        console.error('路由跳转失败:', error)
      }
    }
    
    // 处理查看费用详情
    const handleViewFeeDetail = (fee) => {
      console.log('handleViewFeeDetail被调用，费用ID:', fee.feeId)
      // 先将费用ID存入localStorage，由费用页面读取
      localStorage.setItem('viewFeeDetail', fee.feeId)
      
      // 跳转到费用管理页面
      console.log('即将跳转到StorageFees路由')
      navigateTo('/storage-fees')
    }
    
    return {
      statisticsData,
      recentStorageRecords,
      portAreas,
      unpaidFees,
      recordsLoading,
      areasLoading,
      feesLoading,
      calculateUsage,
      getUsageColor,
      getStatusType,
      formatDate,
      navigateTo,
      handleViewFeeDetail
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.statistic-card {
  height: 100px;
  display: flex;
  align-items: center;
  padding: 20px;
}

.statistic-icon {
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  margin-right: 15px;
}

.blue-bg {
  background-color: rgba(64, 158, 255, 0.2);
  color: #409EFF;
}

.orange-bg {
  background-color: rgba(230, 162, 60, 0.2);
  color: #E6A23C;
}

.green-bg {
  background-color: rgba(103, 194, 58, 0.2);
  color: #67C23A;
}

.purple-bg {
  background-color: rgba(144, 147, 153, 0.2);
  color: #909399;
}

.statistic-icon i {
  font-size: 24px;
}

.statistic-info {
  flex: 1;
}

.statistic-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.statistic-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>